//
//  KuaiVC.m
//  K8彩票
//
//  Created by zhoubo on 2017/6/9.
//  Copyright © 2017年 zhoubo. All rights reserved.
//

#import "KuaiVC.h"
#import "KuaiCollectionViewCell.h"
#import "KuaiCollectionViewLayout.h"
#import "KuaiSelectView.h"
#import "KuaiFotterView.h"

#import "IssueModel.h"

#import "UIViewController+HUD.h"
#import "MBProgressHUD.h"
#import <objc/runtime.h>
#import "Config.h"
#import "CaipiaoHistoryModel.h"

@interface KuaiVC()<UICollectionViewDataSource,UICollectionViewDelegate,ChooseDelegate,CAAnimationDelegate>
@property (weak, nonatomic) IBOutlet KuaiSelectView *selectView;

@property (weak, nonatomic) IBOutlet UIView *lotteryView;


@property (weak, nonatomic) IBOutlet UIButton *titleBtn;

@property (weak, nonatomic) IBOutlet UICollectionView *collectionview;

@property (nonatomic,strong) NSArray* numbers;
@property (nonatomic,strong) NSArray* awards;

@property (nonatomic,assign) NSInteger  totalSelCount;

@property (weak, nonatomic) IBOutlet UILabel *calculateLabel;

@property (nonatomic,assign) NSInteger  beforeSel;


@property(nonatomic,strong) CaipiaoHistoryModel* model;

@property (weak, nonatomic) IBOutlet UILabel *issueLabel;

@property (weak, nonatomic) IBOutlet UIImageView *imgview1;

@property (weak, nonatomic) IBOutlet UIImageView *imgview2;
@property (weak, nonatomic) IBOutlet UIImageView *imgview3;
@property (weak, nonatomic) IBOutlet UILabel *nextIssueLabel;
@property (weak, nonatomic) IBOutlet UILabel *timelabel;


@property (nonatomic,assign) NSInteger issueNo;
@property (nonatomic,strong) NSMutableArray* imgs;

@property (nonatomic,weak) UIView* bottomView;

@property (weak, nonatomic) IBOutlet UIView *xiaZhuView;




@end

@implementation KuaiVC
- (IBAction)confirmBtnClick:(id)sender {
    CGRect frame = self.bottomView.frame;
    [UIView animateWithDuration:1 animations:^{
        self.bottomView.frame = CGRectMake(0, [UIScreen mainScreen].bounds.size.height - 50, [UIScreen mainScreen].bounds.size.width, 50);
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:2 animations:^{
            self.bottomView.alpha = 0;
        } completion:^(BOOL finished) {
            self.bottomView.frame = frame;
            self.bottomView.alpha = 1;
        }];
    }];

}
- (IBAction)dismissBtnClick:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(void)viewDidLoad
{
    [self setbottomview];
    
    self.selectView.backgroundColor = [UIColor colorWithWhite:237/255.0 alpha:1];
    self.collectionview.backgroundColor = [UIColor colorWithWhite:237/255.0 alpha:1];
//    self.collectionview.backgroundColor = [UIColor redColor];
    
    [self.collectionview registerClass:[KuaiCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    self.collectionview .delegate = self;
    self.collectionview.dataSource = self;
    [self.collectionview setCollectionViewLayout:[[KuaiCollectionViewLayout alloc]init]] ;
    self.totalSelCount = 0;
    
    //    //注册头视图
    [self.collectionview registerClass:[KuaiFotterView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"kuaifotter"];
    [self prepareData];
    
    self.selectView.hidden = !IS_OPEN_SWITCH;
    self.xiaZhuView.hidden = !IS_OPEN_SWITCH;
    
    
    if (!IS_OPEN_SWITCH) {

        UILabel* lbl = [[UILabel alloc]init];
        lbl.text = NSLocalizedString(@"暂无其他数据", @"暂无其他数据");
        lbl.frame = CGRectMake(0, 200, ScreenWidth(), 30);
        lbl.textAlignment = NSTextAlignmentCenter;
        lbl.textColor = [UIColor grayColor];
        lbl.font = [UIFont systemFontOfSize:12];
        [self.view addSubview:lbl];
//        CABasicAnimation *animation =  [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
//        //默认是顺时针效果，若将fromValue和toValue的值互换，则为逆时针效果
//        animation.fromValue = [NSNumber numberWithInt:0];
//        animation.toValue =  [NSNumber numberWithFloat:M_PI*2];
//        animation.duration  = 3;
//        animation.autoreverses = NO;
//        animation.fillMode =kCAFillModeForwards;
//        animation.repeatCount = MAXFLOAT; //如果这里想设置成一直自旋转，可以设置为MAXFLOAT，否则设置具体的数值则代表执行多少次
//        [imgview.layer addAnimation:animation forKey:nil];
        
//        /* 旋转 */
//        
//        // 对Y轴进行旋转（指定Z轴的话，就和UIView的动画一样绕中心旋转）
//        CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.y"];
//        animation.delegate = self;
//        
//        // 设定动画选项
//        animation.duration = 2.5; // 持续时间
//        animation.repeatCount = 100; // 重复次数
//        
//        // 设定旋转角度
//        animation.fromValue = [NSNumber numberWithFloat:0.0]; // 起始角度
//        animation.toValue = [NSNumber numberWithFloat:2 * M_PI]; // 终止角度
//        
//        // 添加动画  
//        [imgview.layer addAnimation:animation forKey:@"rotate-layer"];
        

    }
    
    

    
//    self.imgs = [[NSMutableArray alloc]initWithCapacity:6];
//    for (int i = 1; i<7; ++i) {
//        [self.imgs addObject:[UIImage imageNamed:[NSString stringWithFormat:@"%d",i]]];
//    }
//    [self startAnimation:self.imgview1];
//    [self startAnimation:self.imgview3];
//    [self startAnimation:self.imgview2];
    
    [self timeDo];
    NSTimer* timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(timeDo) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];


    
}

-(void)animationDidStart:(CAAnimation *)anim
{
    NSLog(@"start");
}
-(void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
    NSLog(@"stop");
}

-(void)viewWillLayoutSubviews
{

}




-(void)setbottomview
{
    self.beforeSel = -1;
    self.titleBtn.userInteractionEnabled = false;
    //    self.collectionview.backgroundColor = [UIColor redColor];
    
    UIView* view = [[UIView alloc]initWithFrame:CGRectMake(0, [UIScreen mainScreen].bounds.size.height, [UIScreen mainScreen].bounds.size.width, 50)];
    view.backgroundColor = [UIColor purpleColor];
    self.bottomView = view;
    UILabel * lbl = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, view.bounds.size.height)];
    lbl.textAlignment = NSTextAlignmentCenter;
    lbl.text = NSLocalizedString(@"下注成功", @"下注成功");
    lbl.textColor = [UIColor whiteColor];
    [view addSubview:lbl];
    [self.view addSubview:view];
}

//-(void)startAnimation:(UIImageView*)imgview
//{
//    //设置动画数组
//    [imgview setAnimationImages:self.imgs];
//    //设置动画播放次数
//    [imgview setAnimationRepeatCount:10];
//    //设置动画播放时间
//    [imgview setAnimationDuration:0.5];
//    //开始动画
//    [imgview startAnimating];
//    
//    
//}


-(void)prepareData
{
    NSArray* numbers = @[@3,@4,@5,@6,@7,@8,@9,@10,@11,@12,@13,@14,@15,@16,@17,@18];
    NSArray* awards = @[@240,@80,@40,@25,@16,@12,@10,@9,@9,@10,@12,@16,@25,@40,@80,@240];
    
    self.numbers = numbers;
    self.awards = awards;
    
    
}


-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 16;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    KuaiCollectionViewCell * cell = [self.collectionview dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    
    cell.backgroundColor = [UIColor whiteColor];
    
    cell.number = ((NSNumber*)self.numbers[indexPath.row]).integerValue;
    cell.award = ((NSNumber*)self.awards[indexPath.row]).integerValue;
    return cell;
}


-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    

    KuaiCollectionViewCell* cell = [collectionView cellForItemAtIndexPath:indexPath];
    NSLog(@"%ld",cell.isSelected);
    
    cell.isSelect = cell.isSelect == 0 ? 1 : 0;
       NSLog(@"---%ld",cell.isSelect);
 
    if (cell.isSelect) {
        self.totalSelCount += 1;
        cell.backgroundColor = [UIColor redColor];
        [cell settextColor:[UIColor whiteColor]];
    }
    else
    {

        self.totalSelCount -= 1;
        cell.backgroundColor = [UIColor whiteColor];
        [cell settextColor:[UIColor grayColor]];
    }
    
    self.calculateLabel.text = [NSString stringWithFormat:NSLocalizedString(@"共%ld注 %ld元", @"共%ld注 %ld元"),self.totalSelCount,self.totalSelCount*2];
    
    

    
 
}


//  返回头视图
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    //如果是头视图
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
//        UICollectionReusableView *header=[collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"kuaifotter" forIndexPath:indexPath];
//        
//        
//        return header;
    }
//    如果底部视图
        if([kind isEqualToString:UICollectionElementKindSectionFooter]){
    
            KuaiFotterView *fotter=[collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"kuaifotter" forIndexPath:indexPath];
            
            fotter.delegate = self;
            return fotter;
        }
    return nil;
}


-(void)chooseNumbers:(NSInteger)index
{

    
    if (index == 0) {
        
        for (int i = 0; i<16; ++i) {
            NSIndexPath* indexpath = [NSIndexPath indexPathForItem:i inSection:0];
            //前八个非选中
            if (i<8) {
                
                KuaiCollectionViewCell* cell = [self.collectionview cellForItemAtIndexPath:indexpath];
                
                cell.isSelect = false;
                
                cell.backgroundColor = [UIColor whiteColor];
                [cell settextColor:[UIColor grayColor]];
                

            }
            else
            {
                KuaiCollectionViewCell* cell = [self.collectionview cellForItemAtIndexPath:indexpath];
                
                cell.isSelect = true;
                
                cell.backgroundColor = [UIColor redColor];
                [cell settextColor:[UIColor whiteColor]];

                
            }
        }
        
        self.beforeSel = 0;
    }
    else if(index == 1)
    {
        for (int i = 0; i<16; ++i) {
            
            NSIndexPath* indexpath = [NSIndexPath indexPathForItem:i inSection:0];
            
            //前八个选中
            //前八个非选中
            if (i>=8) {
                
                KuaiCollectionViewCell* cell = [self.collectionview cellForItemAtIndexPath:indexpath];
                
                cell.isSelect = false;
                
                cell.backgroundColor = [UIColor whiteColor];
                [cell settextColor:[UIColor grayColor]];

                
                
            }
            else
            {
                KuaiCollectionViewCell* cell = [self.collectionview cellForItemAtIndexPath:indexpath];
                
                cell.isSelect = true;
                
                cell.backgroundColor = [UIColor redColor];
                [cell settextColor:[UIColor whiteColor]];

                
            }


        }

        
    }
    else if (index == 2)
    {
        for (int i = 0; i<16; ++i) {
            
            NSIndexPath* indexpath = [NSIndexPath indexPathForItem:i inSection:0];
            
            //前八个选中
            //前八个非选中
            if (i%2) {
                
                KuaiCollectionViewCell* cell = [self.collectionview cellForItemAtIndexPath:indexpath];
                
                cell.isSelect = false;
                
                cell.backgroundColor = [UIColor whiteColor];
                [cell settextColor:[UIColor grayColor]];

                
                
            }
            else
            {
                KuaiCollectionViewCell* cell = [self.collectionview cellForItemAtIndexPath:indexpath];
                
                cell.isSelect = true;
                
                cell.backgroundColor = [UIColor redColor];
                [cell settextColor:[UIColor whiteColor]];

            }
            
            
        }

    }
    else
    {
        for (int i = 0; i<16; ++i) {
            
            NSIndexPath* indexpath = [NSIndexPath indexPathForItem:i inSection:0];
            

        if (i%2) {
            

            KuaiCollectionViewCell* cell = [self.collectionview cellForItemAtIndexPath:indexpath];
            
            cell.isSelect = true;
            
            cell.backgroundColor = [UIColor redColor];
            [cell settextColor:[UIColor whiteColor]];

            
        }
        else
        {
            KuaiCollectionViewCell* cell = [self.collectionview cellForItemAtIndexPath:indexpath];
            
            cell.isSelect = false;
            
            cell.backgroundColor = [UIColor whiteColor];
            
            [cell settextColor:[UIColor grayColor]];

            
        }
        
    }
    }
    
    self.totalSelCount = 8;
        self.calculateLabel.text = [NSString stringWithFormat:NSLocalizedString(@"共%ld注 %ld元", @"共%ld注 %ld元"),self.totalSelCount,self.totalSelCount*2];
}



/// 请求开奖信息列表
/// 双色球11 大乐透14 排列三16 排列五17 江苏快三75 湖北快三80 安徽快3 76
- (void)requestCaipiaoList:(NSDictionary *)parameters caipiaoid:(NSInteger )caipiaoid{
//    [self showHudInView:self.view hint:@""];
    [[HttpManager getInstance]get:BASE_URL params:parameters successCallback:^(NSString *state, id responseObject) {
        
        NSDictionary *result = [responseObject objectForKey:@"result"];

            CaipiaoHistoryModel *model = [[CaipiaoHistoryModel alloc]initWithDictionary:result];
            
            self.model = model;


//        [self hideHud];
        
    } failCallback:^(NSString *state, id responseObject) {
//        [self hideHud];
    }];
}

-(void)setKind:(NSInteger)kind
{
    _kind = kind;
    
    [self requestCaipiaoList:@{@"appkey":APP_KEY,@"caipiaoid":[NSString stringWithFormat:@"%ld",kind]} caipiaoid:kind]; // 江苏快三
    
}


-(void)setModel:(CaipiaoHistoryModel *)model
{
    _model = model;
    
    //®®®®®®在viewwilllayoutsubviews和viewdidload 和 awakefromxib都没有效果... 在这里才有效果
    [UIView animateWithDuration:1 animations:^{
        self.issueLabel.alpha = 1;
        self.nextIssueLabel.alpha = 1;
        self.timelabel.alpha = 1;
        self.imgview1.alpha = 1;
        self.imgview2.alpha = 1;
        self.imgview3.alpha = 1;
    }];
    
    NSString* issuetext = [model.issueno substringFromIndex:9];
    
    self.issueNo = issuetext.integerValue;
  
    
    
    NSString* number1 = [model.number substringToIndex:1];
    NSString* number2 = [model.number substringWithRange:NSMakeRange(2, 1)];
    NSString* number3 = [model.number substringFromIndex:4];
    
    
//    
//    NSLog(@"%@---%@---%@",model.issueno,model.number,model.opendate);
//    NSLog(@"%ld---%ld---%ld",model.issueno.length,model.number.length,model.opendate.length);
//    
//    [self.imgview1 stopAnimating];
//    [self.imgview2 stopAnimating];
//    [self.imgview3 stopAnimating];
    
    self.imgview1.image = [UIImage imageNamed:number1];
    self.imgview2.image = [UIImage imageNamed:number2];
    self.imgview3.image = [UIImage imageNamed:number3];
    

    
    
    
    NSArray* arr = [model.opendate componentsSeparatedByString:@" "];
    NSArray* ymd = [arr[0] componentsSeparatedByString:@"-"];
    NSArray* hms = [arr[1] componentsSeparatedByString:@":"];
    
    NSString* minute = hms.lastObject;
  
}

-(void)setIssueNo:(NSInteger)issueNo
{
    _issueNo = issueNo;
    self.issueLabel.text = [NSString stringWithFormat:NSLocalizedString(@"%02ld期开奖", @"%02ld期开奖"),issueNo];
    self.nextIssueLabel.text = [NSString stringWithFormat:NSLocalizedString(@"距%02ld期截止", @"距%02ld期截止"),issueNo + 1];
    
}

-(void)timeDo
{
    NSDate *date = [NSDate date];
    NSCalendar *cal = [NSCalendar currentCalendar];
    NSDateComponents *components = [cal components:NSCalendarUnitMinute|NSCalendarUnitSecond fromDate:date];
    
    self.timelabel.text = [NSString stringWithFormat:@"%02ld : %02ld",9-[components minute]%10,59-[components second]];
    if (9-[components minute]%10 == 0 && 59-[components second] == 0) {
        self.issueNo += 1;
    }
    
    
    
}
    
    
    
  
    





@end
